from base import Yaml, Path, build_request, Json
from page import ApiPage


class SeniverseWeatherApi(ApiPage):
    """
    author: ArtLinty
    email: hello@linty.art
    desc: 心知天气 天气类接口业务
    """
    LANG_ZH_HANS = "zh-Hans"
    UNIT_C = "c"

    __config = Yaml.get_config_as_dict(
        Path.get_actual_path_by_current_file(__file__, "api.yml"),
        key="SeniverseWeatherApi"
    )

    def get_now(self, location, language=LANG_ZH_HANS, unit=UNIT_C, sign=None, uid=None, time_stamp=None, key=None):
        """
        获取指定城市的天气实况。
        要求：key 或者 （sign, uid, time_stamp ) 不可同时为 None
        请求示例：
        https://api.seniverse.com/v3/weather/now.json?key=Svt8nM15z02DyvYDt&location=beijing&language=zh-Hans&unit=c
        :param location:
        :param language:
        :param unit:
        :param sign:
        :param uid:
        :param time_stamp:
        :param key:
        :return:
            付费用户可获取全部数据，免费用户只返回天气现象文字、代码和气温3项数据。注：中国城市暂不支持云量和露点温度。
        """
        yml = self.__config["API_NOW"]
        url = self._base_url + yml["NAME"]
        yml_param = yml["PARAM"]
        data = {
            yml_param["LOCATION"]: location,
            yml_param["LANGUAGE"]: language,
            yml_param["UNIT"]: unit,
            yml_param["SIGN"]: sign,
            yml_param["UID"]: uid,
            yml_param["TIMESTAMP"]: time_stamp,
            yml_param["KEY"]: key
        }
        data = self._handle_params(data)
        self.info("[%s]-请求 now.json 接口：url=%s, params=%r" % (__name__, url, data))
        self._req = build_request(
            url=url,
            method=yml["METHOD"],
            params=data
        )

        return self._parse_get_now(self._req.json_dict)

    def _parse_get_now(self, json_dict):
        """
        解析 get_now() 的接口返回值
        :param json_dict:
        :return:
        """

        resp = self._parse_http_resp()

        yml_resp = self.__config["API_NOW"]["RESP"]
        data_key = yml_resp["DATA_KEY"]
        index = yml_resp["INDEX"]
        sub_key_list = yml_resp["SUB_KEY"]

        for key in sub_key_list:
            value = Json.parse_json_dict_value(
                json_dict=json_dict,
                data_key=data_key,
                index=index,
                sub_key=key
            )
            if value:
                resp[key] = value

        return resp
